package com.pengcheng.taskapplication.mvp.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.library.BandCardEditText;
import com.image.imagepicker.ImagePicker;
import com.image.imagepicker.bean.ImageItem;
import com.image.imagepicker.ui.ImageGridActivity;
import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.contants.ConstantValue;
import com.pengcheng.taskapplication.helper.ImageLoader;
import com.pengcheng.taskapplication.model.BindCardModel;
import com.pengcheng.taskapplication.model.IdcardAllOcrModel;
import com.pengcheng.taskapplication.model.IdcardBackOcrModel;
import com.pengcheng.taskapplication.model.IdcardFrontOcrModel;
import com.pengcheng.taskapplication.model.RealNameAuthModel;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenter;
import com.pengcheng.taskapplication.mvp.view.fragment.ConfirmDialogFragment;
import com.pengcheng.taskapplication.net.IView;
import com.pengcheng.taskapplication.util.CheckBankCard;
import com.pengcheng.taskapplication.util.DisplayHelper;
import com.pengcheng.taskapplication.util.SPUtils;
import com.pengcheng.taskapplication.util.ToastUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ZFT on 2020/10/24.
 */

public class UploadIdCard extends BaseActivity implements IView,ConfirmDialogFragment.OnFragmentInteractionListener {

    @BindView(R.id.tv_center_title)
    TextView textView;
    @BindView(R.id.showReverseImage)
    ImageView showReverseImage;
    @BindView(R.id.showImage)
    ImageView showImage;
    @BindView(R.id.tv_apply)
    TextView tv_apply;
    @BindView(R.id.bank_card)
    BandCardEditText bank_card;

    IdcardBackOcrModel idcardBackOcrModel;
    IdcardFrontOcrModel idcardFrontOcrModel;

    private UserPresenter userPresenter;
    private static final int REQUEST_CODE_SELECT = 111;
    private static final int REQUEST_CODE_REVERSE_SELECT = 112;
    private String imagePath="";
    private String imageReversePath="";

    private long certId;
    private long from;
    private long flag;



    @Override
    protected int layoutResID() {
        return R.layout.activity_upload_idcard_layout;
    }

    @Override
    protected void initData() {
        certId=getIntent().getLongExtra("certId",0);
        from =getIntent().getLongExtra("from",0l);
        flag=getIntent().getLongExtra("flag",0);
        userPresenter = new UserPresenter(this);
        textView.setText("电子车牌");
        //需要回显图片，并重新实名并替换token
        if(certId>0&flag==1){
            idcardFrontReOcr(certId);
            idcardBackReOcr(certId);
        }

    }


    @OnClick({R.id.img_back,R.id.upload_sfz_back,R.id.upload_sfz,R.id.tv_apply})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.upload_sfz:
                uploadIdCard();
                break;
            case R.id.upload_sfz_back:
                uploadIdCardReverse();
                break;
            case R.id.tv_apply:
//                String bankCode=bank_card.getBankCardText().toString().trim();
//                if(bankCode==null||bankCode.length()==0||!CheckBankCard.checkBankCard(bankCode)){
//                    ToastUtils.showShortToast("请输入正确的银行卡号");
//                    return;
//                }
                if(idcardFrontOcrModel==null){
                    ToastUtils.showShortToast("请上传身份证正面照");
                    return;
                }
                if(idcardBackOcrModel==null){
                    ToastUtils.showShortToast("请上传身份证正面照");
                    return;
                }

                if(idcardFrontOcrModel!=null&&idcardBackOcrModel!=null){
                    showDialog(idcardFrontOcrModel);
                }

                break;
        }
    }
    public void uploadIdCard(){
        setImagePicker();
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        pickImage();
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(context, "没有权限", Toast.LENGTH_LONG).show();
                    }
                }).start();
    }

    public void uploadIdCardReverse(){
        setImagePicker();
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        pickReverseImage();
                        //showDialog();
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(context, "没有权限", Toast.LENGTH_LONG).show();
                    }
                }).start();
    }

    public void goToPickPic(){
        ImagePicker.getInstance().setSelectLimit(1);
        ImagePicker.getInstance().setCrop(false);
        ImagePicker.getInstance().setShowCamera(true);
        ImagePicker.getInstance().setMultiMode(true);
        Intent intent = new Intent(context, ImageGridActivity.class);
        startActivityForResult(intent, 1110);
    }

    private void setImagePicker() {
        ImagePicker.getInstance().setSelectLimit(1);
        ImagePicker.getInstance().setCrop(true);
        ImagePicker.getInstance().setMultiMode(false);
        ImagePicker.getInstance().setSaveRectangle(true);

        double height=DisplayHelper.getDisplayMetrics(context).widthPixels / (860 / 540);
        double width=DisplayHelper.getDisplayMetrics(context).widthPixels;
        ImagePicker.getInstance().setFocusHeight((int)height);
        ImagePicker.getInstance().setFocusWidth((int)width);
        ImagePicker.getInstance().setOutPutY((int)height);
        ImagePicker.getInstance().setOutPutX((int)width);
    }

    private void realNameAuthV2(IdcardAllOcrModel idcardAllOcrModel){
        userPresenter.realNameAuthV2(idcardAllOcrModel,ConstantValue.RequestKey.realNameAuth);
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        Intent intent = new Intent(context, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
        startActivityForResult(intent, REQUEST_CODE_SELECT);

    }

    /**
     * 正面
     */
    private void pickImage() {
        Intent intent1 = new Intent(context, ImageGridActivity.class);
        startActivityForResult(intent1, REQUEST_CODE_SELECT);
    }
    /**
     * 反面
     */
    private void pickReverseImage() {
        Intent intent1 = new Intent(context, ImageGridActivity.class);
        startActivityForResult(intent1, REQUEST_CODE_REVERSE_SELECT);
    }


    void showDialog(IdcardFrontOcrModel idcardFrontOcrModel) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);

        // Create and show the dialog.
        ConfirmDialogFragment newFragment = ConfirmDialogFragment.newInstance(idcardFrontOcrModel);
        newFragment.show(ft, "dialog");
    }


    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    //Logger.e("xuke", "--->" + images.get(0));
                    imagePath = images.get(0).getPath();
                    userPresenter.idcardFrontOcr(new File(images.get(0).getPath()), ConstantValue.RequestKey.idcardFrontOcr);
                }
            }else if(data != null && requestCode == REQUEST_CODE_REVERSE_SELECT){
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    //Logger.e("xuke", "--->" + images.get(0));
                    imageReversePath = images.get(0).getPath();
                    userPresenter.idcardBackOcr(new File(images.get(0).getPath()), ConstantValue.RequestKey.idcardBackOcr);
                }
            }
        }
    }
    //确认无误
    @Override
    public void onConfirm() {
        if(idcardFrontOcrModel!=null&&idcardBackOcrModel!=null){
            IdcardAllOcrModel model =new IdcardAllOcrModel();
            model.setIdcardFrontPhoto(idcardFrontOcrModel.getImgPath());
            model.setIdcardBackPhoto(idcardBackOcrModel.getImgPath());
            model.setName(idcardFrontOcrModel.getName());
            model.setGender(idcardFrontOcrModel.getGender());
            model.setIdcardCode(idcardFrontOcrModel.getIdcardCode());
            model.setBirthday(idcardFrontOcrModel.getBirthday());
            model.setAddress(idcardFrontOcrModel.getAddress());
            model.setNation(idcardFrontOcrModel.getNation());
            model.setValidity(idcardBackOcrModel.getValidity());
            model.setDepartname(idcardBackOcrModel.getDepartname());
            model.setChannelCode(ConstantValue.channelCode);
            model.setForeverFlag(idcardBackOcrModel.isForeverFlag());
            realNameAuthV2(model);
        }else{

        }
    }
    //取消需要处理，清理当前数据
    @Override
    public void onReply() {

    }

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        if(actionType.equals(ConstantValue.RequestKey.idcardFrontOcr)){
            idcardFrontOcrModel=(IdcardFrontOcrModel)data;
            Glide.with(context).load(Uri.fromFile(new File(imagePath))).into(showImage);
        }
        if(actionType.equals(ConstantValue.RequestKey.idcardBackOcr)){
            idcardBackOcrModel=(IdcardBackOcrModel)data;
            Glide.with(context).load(Uri.fromFile(new File(imageReversePath))).into(showReverseImage);
        }
        //旧的认证回显
        if(actionType.equals(ConstantValue.RequestKey.idcardFrontReOcr)){
            idcardFrontOcrModel=(IdcardFrontOcrModel)data;
            Glide.with(context).load(idcardFrontOcrModel.getImgPath()).into(showImage);
        }
        if(actionType.equals(ConstantValue.RequestKey.idcardBackReOcr)){
            idcardBackOcrModel=(IdcardBackOcrModel)data;
            Glide.with(context).load(idcardBackOcrModel.getImgPath()).into(showReverseImage);
        }

        if(actionType.equals(ConstantValue.RequestKey.realNameAuth)){
            RealNameAuthModel realNameAuthModel = (RealNameAuthModel)data;

//            String bankNum=bank_card.getBankCardText().toString().trim();
//            BindCardModel bindCardModel =new BindCardModel();
//            bindCardModel.setCertId(Long.parseLong(realNameAuthModel.getCertId()));
//            bindCardModel.setBankcardCode(bankNum);
//            bindCardModel.setPhone(SPUtils.getString(context,ConstantValue.SpType.phone));
//            bindCard(bindCardModel);
            Intent intent = new Intent(context, Html5AgressActivity.class);
            intent.putExtra("url","file:///android_asset/instructions.html");
            intent.putExtra("title","办理须知");
            startActivity(intent);
            UploadIdCard.this.finish();






            //跳转到下一步 验证银行卡
//            Intent intent =new Intent(context,BindCardActivity.class);
//            intent.putExtra("certId",realNameAuthModel.getCertId());
//            intent.putExtra("from",from);
//            startActivity(intent);
//            UploadIdCard.this.finish();
        }

        if(actionType.equals(ConstantValue.RequestKey.bindCard)){
            if(code.equals("2")){
                //非工行卡
                Intent intent =new Intent(context,NoICBCCardActivity.class);
                intent.putExtra("bankcardCode",bank_card.getBankCardText().toString().trim());
                intent.putExtra("from",from);
                startActivity(intent);
            }else{
//                //工行卡
//
//                Gson gson= new Gson();
//                Type type =new TypeToken<SmsModel>(){}.getType();
//                SmsModel smsModel= gson.fromJson(gson.toJson(data),type);
//                Intent intent =new Intent(context,ICBCCardActivity.class);
//                intent.putExtra("bankcardCode",bandCardEditText.getBankCardText().toString().trim());
//                intent.putExtra("smsNo",smsModel.getSmsNo());
//                intent.putExtra("from",from);
//                intent.putExtra("certId",certId);
//                startActivity(intent);
                Intent intent =new Intent(context,NoICBCCardActivity.class);
                intent.putExtra("bankcardCode",bank_card.getBankCardText().toString().trim());
                intent.putExtra("from",from);
                startActivity(intent);
            }
            UploadIdCard.this.finish();
        }
    }
    public void bindCard(BindCardModel bindCardModel){
        userPresenter.bindCard(bindCardModel, ConstantValue.RequestKey.bindCard);
    }

    public void idcardFrontReOcr(long certId){
        userPresenter.idcardFrontReOcr(certId,ConstantValue.RequestKey.idcardFrontReOcr);
    }

    public void idcardBackReOcr(long certId){
        userPresenter.idcardBackReOcr(certId,ConstantValue.RequestKey.idcardBackReOcr);
    }



    @Override
    public void onFailed(String code, String msg) {
        ToastUtils.showShortToast(msg);
    }
}
